package cn.edu.zzuli.controller;

import cn.edu.zzuli.service.UserService;
import cn.edu.zzuli.utils.DataGridView;
import cn.edu.zzuli.utils.ResultInfo;
import cn.edu.zzuli.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;

/**
 * Created by CaoShi on 2020/2/14 10:34
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/userList")
    public String toUserList(Model model) {
        List<String> addrList = userService.listAllAddress();
        model.addAttribute("addressList", addrList);
        return "/user/userList";
    }

    @RequestMapping("/list")
    @ResponseBody
    public DataGridView list(UserVO userVO) {
        return userService.getUserForDataGridView(userVO);
    }

    @RequestMapping("/delete")
    @ResponseBody
    public ResultInfo deleteUserById(UserVO userVO) {
        System.out.println("UserController.deleteUserById ---------" + userVO.getId());
        int index = userService.removeUserById(userVO.getId());
        if (index > 0) {
            return ResultInfo.DELETE_SUCCESS;
        } else {
            return ResultInfo.DELETE_ERROR;
        }
    }


    @RequestMapping("/addUser")
    @ResponseBody
    public ResultInfo add(UserVO userVO) {
        System.out.println("UserController.add" + userVO);
        int index = userService.saveUser(userVO);
        if (index > 0) {
            return ResultInfo.SAVE_SUCCESS;
        } else {
            return ResultInfo.SAVE_ERROR;
        }
    }

    @RequestMapping("/updateUser")
    @ResponseBody
    public ResultInfo edit(UserVO userVO) {
        System.out.println("UserController.add" + userVO);
        int index = userService.updateUser(userVO);
        if (index > 0) {
            return ResultInfo.UPDATE_SUCCESS;
        } else {
            return ResultInfo.UPDATE_ERROR;
        }
    }


    @RequestMapping("/batchDelete")
    @ResponseBody
    public ResultInfo batchDelete(@RequestParam(value = "ids[]") Integer[] ids) {
        System.out.println("UserController.batchDelete" + Arrays.toString(ids));

        try {
            userService.batchRemoveUser(ids);
            return ResultInfo.DELETE_SUCCESS;
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResultInfo.DELETE_ERROR;
        }
    }

}
